<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>合作方管理</title>
<%@ include file="../common/importLib.jsp" %>
<link rel="stylesheet" type="text/css" href="../common/css/codeDownload.css">
<script type="text/javascript" src="../common/My97DatePicker/WdatePicker.js"></script> 
<script type="text/javascript" src="../common/jquery-cascade/js/jquery.cityselect.js"></script>
<script type="text/javascript">
	/**
	 * 增删改查参数设置
	 */
	tableTitle = "合作方列表";
	tableURL = getTimeURL("../maintain/partnerInfo/queryListPage.do");
	toolbarView = 2;
	tableColumns = [[{field:'ck',checkbox:true},
	                {field:'id',title:'id',width:0,rowspan:1},
					{field:'opt',title:'操作',width:100,align:'center', rowspan:1,
						formatter:function(value,rowData,rowIndex){	
							if(rowData.roleId == 9){
								var queryUrl = '../maintain/partnerInfo/queryByUserId.do?userId=' + rowData.userId;						
								return "<a title='编辑' class='xxl_linkbutton' iconCls='icon-edit' href='javascript:datagridUpdate(\"" + queryUrl + "\")'>编辑</a>";
							}
						}
					},	
					{field:'partnerName',title:'合作方名称',width:180,rowspan:1},
					{field:'tel',title:'联系电话',width:100,rowspan:1},
					{field:'mobilePhone',title:'关联手机号',width:100,rowspan:1},
					/* {field:'relUserName',title:'关联用户名',width:100,rowspan:1}, 
					{field:'relRecommendCode',title:'关联推广码',width:100,rowspan:1},*/
					{field:'loginCode',title:'管理员账号',width:100,rowspan:1},
					{field:'passwordSrc',title:'账号密码',width:100,rowspan:1},
					{field:'recommendCode',title:'推广码',width:60,rowspan:1},
					{field:'createTimeString',title:'添加日期',width:140,rowspan:1},
					{field:'signTimeString',title:'签订时间',width:140,rowspan:1},
					{field:'deadlineTimeString',title:'合同结束时间',width:140,rowspan:1},
					{field:'sharingProportion',title:'分成比例',width:60,rowspan:1},
					{field:'contractValidYear',title:'合同年限',width:60,rowspan:1},
					{field:'remark',title:'备注',width:200,rowspan:1},
					{field:'recommendCod',title:'二维码',width:80,align:'center', rowspan:1,
						formatter:function(value,rowData,rowIndex){
							if(rowData.roleId == 4){
								
							}else{
								var para = "";
								if(rowData.recommendCode!=""){
									para = "?para="+rowData.recommendCode;
								}else{
									para = "";
								}
								var codeName = rowData.userName + "_"+rowData.loginCode;
								return "<a class='xxl_linkbutton saveCode' iconCls='icon-download' href='javascript:openDownWindow(\"http://"+ host + phoneWebUrl +"person/fast_register.html"+ para +"\",\""+ codeName  +"\");'>下载</a>";
							
							}
						}
					},
					{field:'disableFlag',title:'禁用状态',width:80,align:'center', rowspan:1,
						formatter:function(value,rowData,rowIndex){
							if(rowData.roleId == 4){
								
							}else{
								if(rowData.disableFlag == 0){
									return "<font color='green'>起用</font>";
								}else{
									return "<font color='red'>禁用</font>";
								}
							}
						}
					}]];
	
	var addWidth = 800; //添加窗口宽度
	var addHeight = 450; //添加窗口高度
	var addTitle = "添加合作方信息"; //添加标题
	var updateWidth = 800; //修改窗口宽度
	var updateHeight = 450; //修改窗口高度
	var updateTitle = "修改合作方信息"; //修改标题
	var updateDisableFlagUri = "../maintain/partnerInfo/updateDisableFlag.do"; //禁用、起用记录
	var deleteUri = "../maintain/partnerInfo/deleteByIds.do"; //删除记录
	
	/**
	 * 初始化添加表单
	 */	
	function initAddForm(){	
		$("#roleId").val("9");
		addFormProcess("loginCode","管理员账号",true);	
		ajaxFormValidator("loginCode","管理员账号",1,12,"../maintain/userInfo/loginCodeValidate.do","ascii");
		//ajaxFormValidator("mobilePhone","手机",11,11);
		baseFormValidator("partnerName","合作方名称",2,32);
		changeRecommendCode("add");//推广码
	}
	
	/**
	 * 初始化修改表单
	 */
	function initUpdateForm(jsonObject){	
		$("#loginCodeUpdate").val(jsonObject.loginCode);
		$("#partnerNameUpdate").val(jsonObject.partnerName);
		$("#idUpdate").val(jsonObject.id);
		$("#userIdUpdate").val(jsonObject.userId);
		$("#passwordSrcUpdate").val(jsonObject.passwordSrc);
		$("#mobilePhoneUpdate").val(jsonObject.mobilePhone);
		$("#recommendCodeUpdate").val(jsonObject.recommendCode);
		$("#sharingProportionUpdate").val(jsonObject.sharingProportion);
		$("#remarkUpdate").val(jsonObject.remark);
		$("#signTimeUpdate").val(jsonObject.signTimeString);
		$("#contractValidYearUpdate").numberbox('setValue',jsonObject.contractValidYear);
		updateFormProcess("partnerNameUpdate","合作方名称");
		//ajaxFormValidator("loginCodeUpdate","管理员账号",1,12,"../maintain/userInfo/loginCodeValidate.do","ascii");
		//ajaxFormValidator("mobilePhoneUpdate","手机",11,11);
		baseFormValidator("partnerName","合作方名称",2,32);
		//$("#mobilePhoneUpdate").trigger("blur");
	}
	
	
	/**
	 *打开二维码下载窗口
	 */
	function openDownWindow(urlStr,codeName){
		var downPage = '<div class="codeDownload">'+
			  	'<div class="codeDownload-content">'+
			  		'<div id="code_download"></div>'+
			  		'<select id="codeSize" name="codeSize" class="form-control select-box">'+
			  			'<option value="256">256×256分辨率</option>'+
			  			'<option value="512">512×512分辨率</option>'+
			  			'<option value="1024">1024×1024分辨率</option>'+
			  		'</select>'+
			  		'<a id="download_btn" class="btn download-btn">下载</a>'+
			  		'<a id="cancel_btn" class="btn cancel-btn">取消</a>'+
			  	'</div>'+
			 '</div>';
		$("body").append(downPage);
		$("#code_download").qrcode(urlStr);
		$("#code_download>canvas").width(150);
		$("#code_download>canvas").height(150);
		$("#download_btn").on('click',function(){
			var size = $("#codeSize").val();
			saveCode(urlStr,size,size,codeName);
		})
		$("#cancel_btn").on('click',function(){
			$(".codeDownload").remove();
		})
	}
	/**
	 * 二维码下载
	 */
	function saveCode(content,width,height,codeName){
		width = width?width:512;
		height = height?height:512;
		$('#code_download').html("").qrcode({
			render:"canvas",
			width: width,
			height:height,
			correctLevel:0,
			text:content
		});
		$("#code_download>canvas").width(150);
		$("#code_download>canvas").height(150);
		var myCanvas = $("#code_download>canvas")[0];
	    var image = myCanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=myCode.png");   
	//  window.location=image; // it will save locally
		var a = document.createElement("a");
		codeName = codeName+"_"+new Date().getTime();
		a.download = codeName + ".jpg";
		a.href = image;
		a.click();
		$(".codeDownload").remove();
	}
	/**
	 *	更改推荐码
	 */
	function changeRecommendCode(type){
		$.ajax({
			type : "post",
			url:"../maintain/userInfo/getRecommendCode.do",
			dataType:"json",
			async:true,
			success:function(data){
				if(data){
					if(type==="add"){
						$("#recommendCode").val(data);
					}else if(type==="update"){
						$("#recommendCodeUpdate").val(data);
					}
				}
			}
		})
	}
	
	//新增提交方法
	function addFormSubmit(){
		var params = getFormJson($('#add_form'));
		$.ajax({
			  type: 'POST',
			  url: '../maintain/partnerInfo/add.do',
			  data: params,
			  dataType: 'json',
			  async: false,
			  success: function(data){
				  if(data.err_code ==0){
					  $('#datagrid_add').window('close');
					  $('#datagrid_table').datagrid('reload');
				  }else {
					alert("新增失败！" + data.err_msg);
				  }
			  },
			  error: function(xhr, type){
			    alert('Ajax error!')
			  }
		});
	}
	//更新提交的方法
	function updateFormSubmit(){
		var params = getFormJson($('#update_form'));
		$.ajax({
			  type: 'POST',
			  url: '../maintain/partnerInfo/edit.do',
			  data: params,
			  dataType: 'json',
			  async: false,
			  success: function(data){
				  if(data.err_code ==0){
					  $('#datagrid_update').window('close');
					  $('#datagrid_table').datagrid('reload');
				  }else {
					alert("更新失败！" + data.err_msg);
				  }
			  },
			  error: function(xhr, type){
			    alert('Ajax error!')
			  }
		});
	}
	//将form中的值转换为键值对。
	function getFormJson(frm) {
	    var o = {};
	    var a = $(frm).serializeArray();
	    $.each(a, function () {
	        if (o[this.name] !== undefined) {
	            if (!o[this.name].push) {
	                o[this.name] = [o[this.name]];
	            }
	            o[this.name].push(this.value || '');
	        } else {
	            o[this.name] = this.value || '';
	        }
	    });

	    return o;
	}
	function validPhonoNumber(idInput){
		var mobilePhone = $("#"+idInput).val();
		var flag = validMobilePhone(mobilePhone);
		if(!flag){
			alert("请输入正确的手机号码");
		}
	}
	/**
	* EasyUI DataGrid根据字段动态合并单元格
	* 参数 tableID 要合并table的id
	* 参数 colList 要合并的列,用逗号分隔(例如："name,department,office");
	*/
	/* function mergeCellsByField(tableID, colList) {
	    var ColArray = colList.split(",");
	    var tTable = $("#" + tableID);
	    var TableRowCnts = tTable.datagrid("getRows").length;
	    var tmpA;
	    var tmpB;
	    var PerTxt = "";
	    var CurTxt = "";
	    var alertStr = "";
	    for (j = ColArray.length - 1; j >= 0; j--) {
	        PerTxt = "";
	        tmpA = 1;
	        tmpB = 0;

	        for (i = 0; i <= TableRowCnts; i++) {
	            if (i == TableRowCnts) {
	                CurTxt = "";
	            }
	            else {
	                CurTxt = tTable.datagrid("getRows")[i][ColArray[j]];
	            }
	            if (PerTxt == CurTxt) {
	                tmpA += 1;
	            }
	            else {
	                tmpB += tmpA;
	                
	                tTable.datagrid("mergeCells", {//合并字段
	                    index: i - tmpA,
	                    field: ColArray[j],
	                    rowspan: tmpA,
	                    colspan: null
	                });
	                tTable.datagrid("mergeCells", { //根据ColArray[j]进行合并
	                    index: i - tmpA,
	                    field: "Ideparture",
	                    rowspan: tmpA,
	                    colspan: null
	                });
	               
	                tmpA = 1;
	            }
	            PerTxt = CurTxt;
	        }
	    }
	} */
	//覆盖默认的方法来实现自定义 加载成功后的回调函数
	/* function defualtOnLoadSuccess(data){
		setTimeout(function() {	
			$("#datagrid_table").datagrid("clearSelections");
			$("#datagrid_table").datagrid("clearChecked");
			$(".xxl_linkbutton").linkbutton({plain:true});
			//MathJax.Hub.Queue(["Typeset",MathJax.Hub,document.getElementsByName("body")[0]]);
		}, 10);
		mergeCellsByField('datagrid_table', "partnerName,tel");
	} */
	
</script>
<script type="text/javascript">
</script>
</head>
<body id="layout" class="easyui-layout">
<div style="background: none repeat scroll 0% 0% #EFEFEF; height:75px; padding: 6px 2px; border-bottom: 1px solid #CCC;"
		region="north"  split="false" title="条件查询">
	<form  id="searchForm" >
	<table>
		<tr>
		    <td width ="30px;"></td>
			<td>添加时间：</td><td><input type="text" name="startDate" id="startDate" style="width: 150px;" class="input-style" onclick="WdatePicker({el:'startDate',maxDate:'#F{$dp.$D(\'endDate\')}', dateFmt: 'yyyy-MM-dd HH:mm:ss'})"/>
			<span style="padding: 0 6px 0 2px;">至</span><input type="text" name ="endDate" id="endDate"  style="width: 150px;" class="input-style" onclick="WdatePicker({el:'endDate',minDate:'#F{$dp.$D(\'startDate\')}', dateFmt: 'yyyy-MM-dd HH:mm:ss'})"/></td>
			<td width="50px;"></td>
			<td>合作方名称：</td><td><input type="text" name="partnerName"/> </td>	
			<td>管理员账号：</td><td><input type="text" name="loginCode"/> </td>			
			<td><a class="easyui-linkbutton" id="search" iconCLs="icon-search"  onclick="searchTable()">搜索</a></td>
			<td><a class="easyui-linkbutton" iconCls="icon-undo" onclick="document.getElementById('searchForm').reset();reload();">清空</a></td>
			<td width="40px;"></td>
			
		</tr>
	</table>
	</form>
	</div>
	<div region="center">
	<!-- datagrid信息表 -->
	<table id="datagrid_table"></table>
	<!-- 添加记录 -->
	<style>
		#datagrid_add,#datagrid_update{
			padding:  10px 20px;
		}
	
		#datagrid_add tr,#datagrid_update tr{
		    height: 30px;
		}
		
	</style>
	<div id="datagrid_add">
		<form id="add_form" action="../maintain/partnerInfo/add.do" method="post">
			<input type ="hidden" id="roleId" name="roleId">
			<table width="630" class="xxl_tb_1">
				<tbody>	
					<tr>
						<td class="xxl_td_2">合作方名称：</td>
						<td><input type="text" id="partnerName" name="partnerName"/></td>
						<td><div id="partnerNameTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td width="120" class="xxl_td_2">管理员账号：</td>
						<td ><input type="text" id="loginCode" name="loginCode" onchange="validateSubmitOnce=true"/></td>
						<td><div id="loginCodeTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td class="xxl_td_2">账号密码：</td>
						<td><input type="text" id="passwordSrc" name="passwordSrc" onchange="validateSubmitOnce=true" /></td>
						<td><div id="passwordSrcTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td class="xxl_td_2">联系电话：</td>
						<td><input type="text" id="tel" name="tel" /></td>
					</tr>
					<tr>
						<td class="xxl_td_2">手机号码：</td>
						<td><input type="text" id="mobilePhone" name="mobilePhone" maxlength="11" onchange="validPhonoNumber('mobilePhone')"/></td>
						<td><div id="mobilePhoneTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td class="xxl_td_2">推广码：</td>
						<td><input type="text" id="recommendCode" name="recommendCode" readonly="readonly" style="border: none;"/></td>
						<td>
							<a style="font-size:20px" href="javascript:changeRecommendCode('add');" >
							<span class="l-btn-text"><span class="l-btn-empty pagination-load" style="vertical-align: middle;padding-right: 10px;">&nbsp;&nbsp;</span></span>
							<span style="font-size: 14px; position: relative;top: -4px;color: #000;left: -10px;">更换</span>
							</a>
						</td>
					</tr>
					<tr>
						<td class="xxl_td_2">分成比例：</td>
						<td><input type="text" id="sharingProportion" name="sharingProportion" class="easyui-numberbox" min="0" precision="2" max="1" /></td>
					</tr>
					<tr>
						<td class="xxl_td_2">合同签订时间：</td>
						<td><input type="text" name="signTimeString" id="signTime" style="width: 150px;" class="input-style" onclick="WdatePicker({el:'signTime', dateFmt: 'yyyy-MM-dd HH:mm:ss'})"/></td>
					</tr>
					<tr>
						<td class="xxl_td_2">合同年限：</td>
						<td><input type="text" id="contractValidYear" name="contractValidYear" class="easyui-numberbox" min="0" precision="0" max="100" /></td>
					</tr>
					<tr>
						<td  class="">备注：</td>
						<td colspan="2"><textarea rows="10" cols="35" id="remark" name="remark"></textarea></td>
					</tr>
					<tr>
						<td colspan="3" style="text-align: center">					
							<a class="easyui-linkbutton" iconCls="icon-ok" onclick="addFormSubmit()">添加</a>
							<a class="easyui-linkbutton" iconCls="icon-undo" onclick="document.getElementById('add_form').reset()">重置</a>
							<a class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#datagrid_add').window('close');">取消</a>
						</td>
					</tr>
				</tbody>
			</table>
		</form>
	</div>
	
	<!-- 修改记录 -->
	<div id="datagrid_update">
		<form id="update_form" action="../maintain/partnerInfo/edit.do" method="post">
			<input type="hidden" id="idUpdate" name="id"/>
			<input type="hidden" id="userIdUpdate" name="userId"/>
			<table width="630" class="xxl_tb_1">
				<tbody>
					<tr>
						<td class="xxl_td_2">合作方名称：</td>
						<td><input type="text" id="partnerNameUpdate" name="partnerName"/></td>
						<td><div id="partnerNameUpdateTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td  width="120" class="xxl_td_2">管理员账号：</td>
						<td><input type="text" id="loginCodeUpdate" name="loginCode" disabled /></td>
						<td><div id="loginCodeUpdateTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td class="xxl_td_2">账号密码：</td>
						<td><input type="text" id="passwordSrcUpdate" name="passwordSrc" /></td>
						<td><div id="passwordSrcTip" style="width:250px"></div></td>
					</tr>
					<tr>
						<td class="xxl_td_2">手机号码：</td>
						<td><input type="text" id="mobilePhoneUpdate" name="mobilePhone" maxlength="11" onchange="validPhonoNumber('mobilePhoneUpdate')" /></td>
						<!-- <td><div  style="width:280px;color:red;">修改手机号码，会涉及到代理人的变更，谨慎修改</div></td> -->
					</tr>
					<tr>
						<td class="xxl_td_2">推广码：</td>
						<td><input id="recommendCodeUpdate" readonly="readonly"  style="border:none"/></td>
					</tr>
					<tr>
						<td class="xxl_td_2">分成比例：</td>
						<td><input type="text" id="sharingProportionUpdate" name="sharingProportion" class="easyui-numberbox" min="0" precision="2" max="1" /></td>
					</tr>
					<tr>
						<td class="xxl_td_2">合同签订时间：</td>
						<td><input type="text" name="signTimeString" id="signTimeUpdate" style="width: 150px;" class="input-style" onclick="WdatePicker({el:'signTimeUpdate', dateFmt: 'yyyy-MM-dd HH:mm:ss'})"/></td>
					</tr>
					<tr>
						<td class="xxl_td_2">合同年限：</td>
						<td><input type="text" id="contractValidYearUpdate" name="contractValidYear" class="easyui-numberbox" min="0" precision="0" max="100" /></td>
					</tr>
					<tr>
						<td  class="xxl_td_2">备注：</td>
						<td colspan="2">
							<textarea rows="10" cols="35" id="remarkUpdate" name="remark"></textarea>
						</td>
					</tr>
					<tr>
						<td colspan="3" style="text-align: center">
							<a class="easyui-linkbutton" iconCls="icon-ok" onclick="updateFormSubmit()">修改</a>		
							<a class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#datagrid_update').window('close');">取消</a>
						</td>
					</tr>
				</tbody>
			</table>
		</form>
	</div>
</body>
</html>